package com.itheima.app.interceptor;

import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson.JSON;
import com.itheima.domain.db.User;
import com.itheima.util.ConstantUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.time.Duration;

@Component
public class TokenInterceptor implements HandlerInterceptor {

    @Autowired
    StringRedisTemplate stringRedisTemplate;

    @Override
    //前置处理
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        //1.获取指定的请求头(token)
        String token = request.getHeader("Authorization");

        //2.判断是否能获取user,若不能返回401
        if (StrUtil.isNotBlank(token)) {
            String value = stringRedisTemplate.opsForValue().get(ConstantUtil.USER_TOKEN + token);

            if (StrUtil.isNotBlank(value)) {
                User user = JSON.parseObject(value, User.class);

                //3.若可以获取,将user绑定到当前线程中
                UserHolder.set(user);

                //4.token的续期
                stringRedisTemplate.opsForValue().set(ConstantUtil.USER_TOKEN+token,value, Duration.ofDays(30));

                //5.放行
                return true;
            }
        }



        //若获取不到token或者解析不了token,返回401
        response.setStatus(401);
        return false;
    }

    @Override
    //最终处理(响应完成之前的处理)
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        //解绑
        UserHolder.remove();
    }
}
